<template>
  <ContentWrap>
    <!-- 查询区域 -->
    <el-form :model="form" inline>
      <el-form-item label="商品名称">
        <el-select
          v-model="form.product_id"
          placeholder="请输入商品名称"
          :filterable="true"
          :clearable="true"
          :remote="true"
          :remote-method="getProductOptions"
          :loading="selectLoading"
          style="width: 200px"
        >
          <el-option
            v-for="item in productList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="发货单号">
        <el-input v-model="form.serial_number" placeholder="请输入发货单号" style="width: 200px" />
      </el-form-item>
      <el-form-item label="原仓库">
        <el-tree-select
          v-model="form.old_wid"
          :data="warehouseList"
          placeholder="请选择"
          style="width: 180px"
          clearable
        />
      </el-form-item>
      <el-form-item label="目的地仓库">
        <el-tree-select
          v-model="form.new_wid"
          :data="warehouseList"
          placeholder="请选择"
          style="width: 180px"
          clearable
        />
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="form.create_time_range"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          style="width: 250px"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          @change="handleDateChange"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="initialize">查询</el-button>
        <el-button icon="Refresh" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 表格区域 -->
    <el-table
      :data="dataList"
      highlight-current-row
      stripe
      border
      v-loading="tableLoading"
      :cell-style="{ textAlign: 'center' }"
      :header-cell-style="{ textAlign: 'center' }"
    >
      <el-table-column label="id" prop="id" min-width="50" />
      <el-table-column label="物流公司" prop="company_name" min-width="120" />
      <el-table-column label="发货单号" prop="serial_number" min-width="120" />
      <el-table-column label="发货时间" prop="ship_date" min-width="120" />
      <el-table-column label="到货时间" prop="arrival_date" min-width="120" />
      <el-table-column label="实际到货日期" prop="real_arrival_date" min-width="120" />
      <el-table-column label="物流单号" prop="logistics_no" min-width="120" />
      <!-- <el-table-column label="成本" prop="cost" min-width="80" /> -->
      <el-table-column prop="cost" label="成本" width="160">
        <template #default="{ row }">
          <div v-for="(item, index) in row.cost" :key="index">
            <span>{{ useEnumeratePicker(operatorOptions.costing, item.type) }}:</span>
            <span>{{ item.amount }}</span>
            <span>{{
              useEnumeratePicker(operatorOptions.currency, item.transaction_currency_id)
            }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="status_value" min-width="100" />
      <el-table-column label="备注" prop="notes" min-width="120" :show-overflow-tooltip="true" />
      <!-- <el-table-column label="创建人" prop="creator" min-width="100" /> -->
      <el-table-column label="创建时间" prop="create_time" min-width="160" />
      <el-table-column label="操作" fixed="right" width="350">
        <template #default="{ row }">
          <div class="flex flex-wrap justify-center gap-y-10px">
            <el-button
              v-hasPermi="['AllotManagementCancel']"
              v-if="row.status !== 2 && row.status !== 3"
              type="danger"
              @click="handleCancel(row)"
              size="small"
            >
              取消
            </el-button>
            <el-button
              v-hasPermi="['AllotManagementDelay']"
              v-if="row.status !== 2 && row.status !== 3"
              type="warning"
              @click="handleDelay(row)"
              size="small"
            >
              延期到仓
            </el-button>

            <el-button
              v-hasPermi="['AllotManagementStore']"
              v-if="row.status !== 2 && row.status !== 3"
              type="primary"
              @click="handleWarehouseIn(row)"
              size="small"
            >
              入库
            </el-button>
            <el-button v-if="row.status !== 2" size="small" @click="handleEdit(row)"
              >编辑</el-button
            >

            <el-button size="small" type="success" @click="handleDetail(row)">详情</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="paginationTotal"
      v-model:page="pageIndex"
      v-model:limit="pageSize"
      @pagination="initialize"
    />
  </ContentWrap>

  <!-- 编辑弹窗 -->
  <DialogEdit v-model:dialogVisible="editDialogVisible" :row="currentRow" @refresh="initialize" />
  <!-- 延期到仓 -->
  <el-dialog v-model="delayDialogVisible" title="延期到仓" width="800px">
    <el-form :model="delayForm" label-width="100px">
      <el-form-item label="实际到货日期">
        <ElDatePicker
          v-model="delayForm.delay_time"
          type="date"
          placeholder="请选择实际到货日期"
          style="width: 100%"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          :disabled-date="(date) => date.getTime() < new Date(currentRow.arrival_date).getTime()"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <BaseButton @click="delayDialogVisible = false">取消</BaseButton>
      <BaseButton type="primary" @click="handleConfirm">确认</BaseButton>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useEnumeratePicker } from '@/utils'
import dayjs from 'dayjs'
import Pagination from '@/components/Pagination/index.vue'
import { ContentWrap } from '@/components/ContentWrap'
import {
  getTransferListApi,
  getSecondWarehouseListApi,
  cancelTransferApi,
  warehouseDelayApi
} from '@/api/warehouse'
import { getListApi as getProductListApi } from '@/api/product'
import type { TransferListParams, TransferListItem } from '@/api/warehouse/types'
import DialogEdit from './components/DialogEdit/index.vue'
import { useRouter } from 'vue-router'
import { getOrderEnumApi } from '@/api/order'
const { t } = useI18n()

const { push } = useRouter()

const tableLoading = ref(false)
const dataList = ref<TransferListItem[]>([])
const paginationTotal = ref(0)
const editDialogVisible = ref(false)
const currentRow = ref<any>({})
const selectLoading = ref(false)

const form = ref<
  TransferListParams & {
    create_time_range?: [string, string] | undefined
    serial_number?: string | undefined
  }
>({
  product_id: '',
  serial_number: '',
  old_wid: '',
  new_wid: '',
  logistics_no: '',
  start_time: '',
  end_time: '',
  create_time_range: undefined,
  pageIndex: '1',
  pageSize: '20'
})

// 分页数据的计算属性，用于双向绑定
const pageIndex = computed({
  get: () => parseInt(form.value.pageIndex || '1'),
  set: (val: number) => {
    form.value.pageIndex = val.toString()
  }
})

const pageSize = computed({
  get: () => parseInt(form.value.pageSize || '20'),
  set: (val: number) => {
    form.value.pageSize = val.toString()
  }
})

const warehouseList = ref<any[]>([])
const productList = ref<Array<{ label: string; value: string; id: string }>>([])

// 商品联想搜索
const getProductOptions = async (value: string) => {
  if (value) {
    selectLoading.value = true
    try {
      const resp = await getProductListApi({ cname: value })
      if (resp.code === 0 && resp.data?.list) {
        productList.value = resp.data.list.map((item: any) => ({
          label: item.cname,
          value: item.id.toString(),
          id: item.id.toString()
        }))
      }
    } catch (error) {
      console.error('获取商品列表失败:', error)
    } finally {
      selectLoading.value = false
    }
  }
}

// 处理日期变化
const handleDateChange = (dates: [string, string] | null) => {
  if (dates && dates.length === 2) {
    form.value.start_time = dates[0]
    form.value.end_time = dates[1]
  } else {
    form.value.start_time = ''
    form.value.end_time = ''
  }
}

// 获取仓库列表
const getWarehouseList = async () => {
  try {
    const res = await getSecondWarehouseListApi({ disabled: false })
    if (res?.data?.list) {
      // 直接赋值，保持原有的树形结构
      warehouseList.value = res.data.list
    } else {
      warehouseList.value = []
    }
  } catch (error) {
    console.error('获取仓库列表失败:', error)
    warehouseList.value = []
  }
}

// 查询方法
const initialize = async () => {
  tableLoading.value = true
  try {
    const params = {
      product_id: form.value.product_id || undefined,
      old_wid: form.value.old_wid || undefined,
      new_wid: form.value.new_wid || undefined,
      logistics_no: form.value.logistics_no || undefined,
      start_time: form.value.start_time || undefined,
      end_time: form.value.end_time || undefined,
      pageIndex: form.value.pageIndex,
      pageSize: form.value.pageSize,
      serial_number: form.value.serial_number || undefined
    }

    const resp = await getTransferListApi(params)
    if (resp.code === 0) {
      dataList.value = resp.data.list
      paginationTotal.value = resp.data.total
    }
  } catch (error) {
    console.error('获取调拨单列表失败:', error)
  } finally {
    tableLoading.value = false
  }
}

// 重置方法
const reset = () => {
  form.value = {
    product_id: '',
    serial_number: '',
    old_wid: '',
    new_wid: '',
    logistics_no: '',
    start_time: '',
    end_time: '',
    create_time_range: undefined,
    pageIndex: '1',
    pageSize: '20'
  }
  productList.value = []
  initialize()
}

// 编辑、详情操作
const handleEdit = (row: TransferListItem) => {
  currentRow.value = row
  editDialogVisible.value = true
}

const handleDetail = (row: TransferListItem) => {
  push({
    path: `/warehouse/allot-management/detail`,
    query: { id: row.id.toString() }
  })
}

const operatorOptions = ref<Record<string, any>>({})
const getDropDownBoxInfo = async () => {
  try {
    const resp = await getOrderEnumApi({ field: 'all' })
    operatorOptions.value = resp.data
  } catch (error) {}
}
//点击取消
const handleCancel = (row: Record<string, any>) => {
  ElMessageBox.confirm(t('orderReturn.confirmCancel'), t('purchase.logistics.tips'), {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      let res = await cancelTransferApi({
        id: row.id
      })
      console.log('res', res)
      if (res.code == 0) {
        ElMessage.success(t('orderReturn.cancelSuccess'))
        initialize()
      }
    })
    .catch(() => {})
}
//入库
const handleWarehouseIn = (row: TransferListItem) => {
  currentRow.value = { ...row, warehouseIn: true }
  editDialogVisible.value = true
}
//延期到仓
const handleDelay = (row: TransferListItem) => {
  currentRow.value = row
  delayDialogVisible.value = true
}
// 初始化
onActivated(() => {
  getWarehouseList()
  initialize()
  getDropDownBoxInfo()
})
const delayDialogVisible = ref(false)
const delayForm = ref({
  delay_time: ''
})
const handleConfirm = async () => {
  console.log('delayForm', delayForm.value)
  if (!delayForm.value.delay_time) {
    ElMessage.error('请选择延期到仓时间')
    return
  }
  let res = await warehouseDelayApi({
    id: currentRow.value?.id,
    real_arrival_date: delayForm.value.delay_time
  })
  if (res.code == 0) {
    ElMessage.success('延期到仓成功')
    delayDialogVisible.value = false
    initialize()
  }
}
</script>

<style lang="less" scoped></style>
